package com.cz.nongyetongv5.activity;

import java.io.File;
import java.io.FilenameFilter;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.GoHomeUtil;
import com.cz.nongyetongv5.utils.HttpUtils;
import com.cz.nongyetongv5.utils.ImageUtil;
import com.cz.nongyetongv5.utils.HttpUtils.OnRequestExecuted;

/**
 * 版本信息
 *
 * @author Mr
 *
 */
@SuppressLint("NewApi")
public class BanBenXinxiActivity extends Activity implements
		View.OnClickListener {

	/**
	 * 退出的按钮
	 */
	private ViewGroup btnBack = null;

	private ViewGroup rlUpdate = null;

	private TextView tvVersion = null;

	private EditText edtLog = null;

	private User user;

	private InitApplication application = null;

	@Override
	protected void onDestroy() {

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().remove(this);

		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().add(this);

		setContentView(R.layout.banbenxinxi);

		application = (InitApplication) getApplicationContext();

		edtLog = (EditText) findViewById(R.id.edtLog);

		// 没有新版本
		if (!application.hasNewVersion()) {

			StringBuffer sbLog = new StringBuffer();

			if (application.getMaxVersion() != null
					&& application.getMaxVersion().getLog().size() > 0) {

				for (int i = 0; i < application.getMaxVersion().getLog().size(); i++) {
					sbLog.append((i + 1) + "、"
							+ application.getMaxVersion().getLog().get(i));

					sbLog.append("\n");
				}
			} else {

				sbLog.append("尚未链接网络,无法获取版本信息...");

			}
			edtLog.setText(sbLog.toString());

			edtLog.setVisibility(View.VISIBLE);
		} else {
			edtLog.setVisibility(View.GONE);
		}

		btnBack = (ViewGroup) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(this);

		rlUpdate = (ViewGroup) findViewById(R.id.rlUpdate);

		tvVersion = (TextView) findViewById(R.id.tvVersion);

		rlUpdate.setClickable(true);

		rlUpdate.setOnClickListener(this);

		if (application.hasNewVersion()) {

			tvVersion.setTextColor(Color.RED);
			tvVersion.setText("发现新版本");

		} else {

			tvVersion.setTextColor(Color.parseColor("#C1C3C3"));

			tvVersion.setText(application.getVersion().getVersion());

		}

		user = (User) getIntent().getSerializableExtra("user");

		loadRightTitle();

	}

	/**
	 * 加载去主页的按钮
	 */
	public void loadRightTitle() {

		ViewGroup btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		View view = GoHomeUtil.createPopView(getApplicationContext(),
				new String[] { "主页" });

		// 弹出更多的菜单
		final PopupWindow pop = new PopupWindow(view,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);

		// 需要设置一下此参数，点击外边可消失
		pop.setBackgroundDrawable(new BitmapDrawable());

		// 设置点击窗口外边窗口消失
		pop.setOutsideTouchable(true);

		// 设置此参数获得焦点，否则无法点击
		pop.setFocusable(true);

		final Button btn01 = (Button) pop.getContentView().findViewWithTag(
				"btn0");

		OnClickListener menuOnClick = new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (v == btn01) {
					GoHomeUtil.goHome(getApplicationContext());
				}
			}
		};

		btn01.setOnClickListener(menuOnClick);

		btnMeanMore = (ViewGroup) findViewById(R.id.btnMeanMore);

		btnMeanMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (pop.isShowing()) {
					// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
					pop.dismiss();
				} else {
					// 显示窗口
					pop.showAsDropDown(v);
				}

			}
		});

	}

	@Override
	public void onClick(View v) {
		if (v == btnBack) {
			this.finish();
		}

		if (v == rlUpdate) {
			if (!CanUpData()) {
				Toast.makeText(BanBenXinxiActivity.this,
						"您还有未上传完的记录文件，请上传完成后再更新", Toast.LENGTH_SHORT).show();
				return;
			}

			if (application.hasNewVersion()) {

				final CustomDialog updateDialog = new CustomDialog(
						BanBenXinxiActivity.this);

				updateDialog.setHeightPercent(0.6F);

				View view = getLayoutInflater().inflate(R.layout.start_update,
						null);

				TextView tvUpdateLog = (TextView) view
						.findViewById(R.id.tvUpdateLog);

				tvUpdateLog.setText(application.getUpdateLog());

				updateDialog.setView(view);

				updateDialog.setTitle("程序更新(更新版本\u0020:\u0020"
						+ application.getMaxVersion().getVersion() + ")");

				updateDialog.setOnActionClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						updateDialog.dismiss();

						Toast.makeText(BanBenXinxiActivity.this,
								"正在为您后台更新..您可以继续工作..", Toast.LENGTH_LONG)
								.show();

						String apkUrl = getString(R.string.new_version_url);

						apkUrl = apkUrl.replaceAll("region_code",
								new ConfigUtil(getResources()).getRegionCode());

						final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

						DownloadManager.Request request = new DownloadManager.Request(
								Uri.parse(apkUrl));

						request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
								| DownloadManager.Request.NETWORK_WIFI);

						request.setTitle("更新");
						request.setDescription("正在为您下载更新..");
						//
						request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

						request.setMimeType("application/cn.trinea.download.file");

						final File file = ImageUtil.getThisAppDataFile();

						File[] childs = file.listFiles(new FilenameFilter() {

							@Override
							public boolean accept(File dir, String filename) {

								if (filename.startsWith("newapp")) {

									return true;
								}

								return false;
							}
						});

						/**
						 * 进行文件的清理
						 */
						for (File child : childs) {
							child.delete();
						}

						final File apkFile = new File(file, "newapp.apk");

						request.setDestinationUri(Uri.fromFile(apkFile));

						request.setVisibleInDownloadsUi(true);

						final long downloadId = downloadManager
								.enqueue(request);

						IntentFilter filter = new IntentFilter(
								DownloadManager.ACTION_DOWNLOAD_COMPLETE);

						BroadcastReceiver receiver = new BroadcastReceiver() {
							@Override
							public void onReceive(Context context, Intent intent) {
								long reference = intent.getLongExtra(
										DownloadManager.EXTRA_DOWNLOAD_ID, -1);

								if (downloadId == reference) {

									if (apkFile.exists()) {

										installApk(apkFile);

									}
								}
							}
						};
						getApplicationContext().registerReceiver(receiver,
								filter);

						IntentFilter clickItemFilter = new IntentFilter(
								DownloadManager.ACTION_NOTIFICATION_CLICKED);

						BroadcastReceiver clickItemReceiver = new BroadcastReceiver() {
							@Override
							public void onReceive(Context context, Intent intent) {
								String extraID = DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS;
								long[] references = intent
										.getLongArrayExtra(extraID);
								for (long reference : references)
									if (reference == downloadId) {

										Toast.makeText(getApplicationContext(),
												"下载更新完成后会自动打开...",
												Toast.LENGTH_SHORT).show();

									}
							}
						};

						getApplicationContext().registerReceiver(
								clickItemReceiver, clickItemFilter);

					}
				});

				updateDialog.setOnCancleClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						updateDialog.dismiss();
					}
				});

				if (!application.getMaxVersion().isMust()) {

					updateDialog
							.setOnCancleClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {

									updateDialog.dismiss();
								}
							});
					updateDialog.setCancleTxt("稍后再说");

				}

				updateDialog.setActionTxt("立即更新");

				updateDialog.show();

			} else {

				// 检测新版本
				tvVersion.setText("正在检测新版本...");

				if (CommonConstants.isNetworkConnected(this)) {

					// �@得新版本

					new AsyncTask<Integer, Integer, Integer>() {

						@Override
						protected Integer doInBackground(Integer... params) {
							HttpUtils httpUtils = HttpUtils.getInstance();

							httpUtils
									.setOnRequestExecuted(new OnRequestExecuted() {

										@Override
										public void onRequestExecuted(
												int responseCode,
												String responseBody) {

											try {
												JSONObject jsonObject = new JSONObject(
														responseBody);

												String version = jsonObject
														.getString("version");

												boolean must = jsonObject
														.getBoolean("must");

												application.getMaxVersion()
														.setVersion(version);

												JSONArray logArrJson = jsonObject
														.getJSONArray("log");

												application.getMaxVersion()
														.getLog().clear();

												for (int i = 0; i < logArrJson
														.length(); i++) {

													String log = logArrJson
															.getString(i);

													application.getMaxVersion()
															.getLog().add(log);

												}

												application.getMaxVersion()
														.getImageDatas()
														.clear();

												JSONArray imageArray = null;

												if (jsonObject.has("images")) {

													imageArray = jsonObject
															.getJSONArray("images");

												}

												if (imageArray != null
														&& imageArray.length() > 0) {

													for (int i = 0; i < imageArray
															.length(); i++) {

														String imageUrl = imageArray
																.getString(i);

														Map<String, Bitmap> imageMap = new HashMap<String, Bitmap>();

														imageMap.put(imageUrl,
																null);

														application
																.getMaxVersion()
																.getImageDatas()
																.add(imageMap);

													}
												}

												application.getMaxVersion()
														.setMust(must);

											} catch (Exception e) {
											}

											try {
												PackageManager packageManager = getPackageManager();
												// getPackageName()是你当前类的包名，0代表是获取版本信息
												PackageInfo packInfo = packageManager
														.getPackageInfo(
																getPackageName(),
																0);

												application
														.getVersion()
														.setVersion(
																packInfo.versionName);
											} catch (NameNotFoundException e) {
											}

										}
									});

							String requestUrl = getString(R.string.get_version_url);

							requestUrl = requestUrl.replaceAll("region_code",
									new ConfigUtil(getResources())
											.getRegionCode());

							httpUtils.sendRequest(requestUrl, null, "GET",
									"UTF-8", null, null, null);

							return null;
						}

						protected void onPostExecute(Integer result) {
							// // 初始化

							if (!application.hasNewVersion()) {

								tvVersion.setTextColor(Color
										.parseColor("#C1C3C3"));

								tvVersion.setText(application.getVersion()
										.getVersion());

								Toast.makeText(BanBenXinxiActivity.this,
										"已经是最新版本", Toast.LENGTH_LONG).show();

								// 没有新版本

								StringBuffer sbLog = new StringBuffer();

								if (application.getMaxVersion() != null
										&& application.getMaxVersion().getLog()
										.size() > 0) {

									for (int i = 0; i < application
											.getMaxVersion().getLog().size(); i++) {
										sbLog.append((i + 1)
												+ "、"
												+ application.getMaxVersion()
												.getLog().get(i));

										sbLog.append("\n");
									}
								}
								edtLog.setText(sbLog.toString());

								edtLog.setVisibility(View.VISIBLE);

							} else {
								tvVersion.setTextColor(Color.RED);
								tvVersion.setText("发现新版本");
								BanBenXinxiActivity.this.onClick(rlUpdate);
							}

						};

					}.execute();

				} else {

					Toast.makeText(this, getString(R.string.error_no_network),
							Toast.LENGTH_LONG).show();

					tvVersion.setText(application.getVersion().getVersion());
				}
			}

		}
	}

	private void installApk(File file) {
		Intent intent = new Intent();

		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		startActivity(intent);

		this.finish();
	}

	public boolean CanUpData() {
		File appDataFile = ImageUtil.getThisAppDataFile();
		if (!appDataFile.exists()) {
			return true;
		} else if (check_DuChaXunCha(appDataFile)
				&& check_ChanPinJianCe(appDataFile)
				&& check_JianDuJianCha(appDataFile)) {
			return true;
		} else
			return false;

	}

	private boolean check_JianDuJianCha(File appDataFile) {
		// TODO Auto-generated method stub
		File jianDuJianChaDataFilse = new File(appDataFile, "jiandujiancha");
		if (!jianDuJianChaDataFilse.exists()) {
			return true;
		}
		File jianDuJianChaListDataFilse = new File(jianDuJianChaDataFilse,
				"list");
		if (!jianDuJianChaListDataFilse.exists()) {
			return true;
		} else {
			File[] fileList = jianDuJianChaListDataFilse.listFiles();// 得到该文件夹下的所有文件和文件夹列表
			if (fileList.length > 0)
				return false;
		}
		return true;
	}

	private boolean check_ChanPinJianCe(File appDataFile) {
		// TODO Auto-generated method stub
		File chanPinJianCeDataFilse = new File(appDataFile, "chanpinjiance");
		if (!chanPinJianCeDataFilse.exists()) {
			return true;
		}
		File chanPinJianCeListDataFilse = new File(chanPinJianCeDataFilse,
				"list");
		if (!chanPinJianCeListDataFilse.exists()) {
			return true;
		}
		if (!chanPinJianCeListDataFilse.exists()) {
			return true;
		} else {
			File[] fileList = chanPinJianCeListDataFilse.listFiles();// 得到该文件夹下的所有文件和文件夹列表
			if (fileList.length > 0)
				return false;
		}
		return true;
	}

	private boolean check_DuChaXunCha(File appDataFile) {
		// TODO Auto-generated method stub
		File duChaXunChaDataFile = new File(appDataFile, "duchaxuncha");
		if (!duChaXunChaDataFile.exists()) {
			return true;
		}
		File duChaXunChaListDataFile = new File(duChaXunChaDataFile, "list");

		if (!duChaXunChaListDataFile.exists()) {
			return true;
		} else {
			File[] fileList = duChaXunChaListDataFile.listFiles();// 得到该文件夹下的所有文件和文件夹列表
			if (fileList.length > 0)
				return false;
		}
		return true;
	}
}
